package com.wsx.ones.user;

import com.google.gson.Gson;
import com.wsx.ones.core.model.CoreCache;
import com.wsx.ones.core.redis.RedisClientTemplate;
import com.wsx.ones.ehcache.UserEhcacheManager;
import com.wsx.ones.finalstr.common.RedisFinalUtil;
import com.wsx.ones.user.signup.vo.UserSignupVo;
import com.wsx.ones.web.util.PojoCopy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

/**
 * Created by wangshuaixin on 16/12/27.
 */
public abstract class UserBaseService {

    @Autowired
    protected RedisClientTemplate redisClientTemplate;

    /**
     * 抽象父类设置用户缓存的方法
     * @return
     */
    public boolean setUserToken(UserSignupVo userSignupVo, boolean ifEhcache) {
        CoreCache coreCache = PojoCopy.copy(userSignupVo, CoreCache.class);
        if (ifEhcache) {
            UserEhcacheManager.getInstance().setCoreCache(userSignupVo.getToken(),coreCache);
        }
        Gson gson = new Gson();
        //
        if (StringUtils.isEmpty(redisClientTemplate.set(userSignupVo.getToken(), gson.toJson(coreCache),
                    RedisFinalUtil.DB_USER_TOKEN, RedisFinalUtil.TOKEN_EXPIRE))) {
            return false;
        }
        return true;
    }

    /**
     * 根据token获得用户信息
     * @param token
     * @param ifEhcache
     * @return
     */
    public CoreCache getUserToken(String token, boolean ifEhcache) {
        CoreCache coreCache = null;
        if (ifEhcache) {
            coreCache = UserEhcacheManager.getInstance().getCoreCache(token);
        }
        if (null == coreCache) {
            String cache = redisClientTemplate.get(token, RedisFinalUtil.DB_USER_TOKEN);
            if (!StringUtils.isEmpty(cache)) {
                Gson gson = new Gson();
                coreCache = gson.fromJson(cache, CoreCache.class);
            }
        }
        return coreCache;
    }
}
